﻿package{
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
    import flash.events.Event;
	
	public class Main extends Sprite
	{
		private var ball:Ball;
		private var dis:Number;
		private var speedX:Number;
		private var speedY:Number;
		private var r:int;
		private var fraction:Number;  
		private var repul:Number;
		private var d:int;   
		
		public function Main ():void
		{
			init();
		}
		private function init():void
		{
			// set stage property
			this.stage.align = StageAlign.TOP_LEFT;
			this.stage.scaleMode = StageScaleMode.NO_SCALE;
			this.stage.frameRate = 32;
			this.stage.stageWidth = 550;
			this.stage.stageHeight = 400;
			
			r=20;
			d=100;          //mouse range
			speedX=0;
			speedY=0;
			repul=0;
			fraction=0.95;  //fraction makes the ball slow down
			
			//draw ball
			ball = new Ball(0,0,0xFFCC33,20);
			ball.x=275 , ball.y=200;
			addChild(ball);
			
			this.stage.addEventListener(Event.ENTER_FRAME,Move);
		}
		private function Move(e:Event):void
		{
			//ball & mouse distance
			dis = Math.sqrt((mouseX-ball.x)*(mouseX-ball.x)+(mouseY-ball.y)*(mouseY-ball.y));
			
			//bump border
			if (ball.x<=r) {       //left
				speedX*=-0.5;
				ball.x=20;
			}
			if (ball.x>=stage.stageWidth-r) {    //right

				speedX*=-0.5;
				ball.x=stage.stageWidth-r;
			}
			if (ball.y<=20) {     //top

				speedY*=-0.5;
				ball.y=20;
			}
			if (ball.y>=stage.stageHeight-r) {   //ground

				speedY*=-0.5;
				ball.y=stage.stageHeight-r;
			}
			if (dis<=d) {

				repul=6-dis * 0.01;   //Repulsion-dis*0.01 
				speedX+=repul*(ball.x-mouseX)/dis;   //x acceleration
				speedY+=repul*(ball.y-mouseY)/dis;   //y acceleration
				
				//move the ball
				ball.x+=speedX;
				ball.y+=speedY;

			}
			
			//stop the ball
			ball.x+=speedX;
			ball.y+=speedY;
			
			//add fraction 
			speedX*=fraction;
			speedY*=fraction;


			
		}
	}
}